<?php

namespace App\Models\CacheModel\consult;

use App\Models\Api\BaseCache;
use app\zyhsapi\model\ZyhsConsultChatRtcRecord;

class AppConsultGift extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_consult_gift';

    protected $cacheModel = 'voice_consult.consult_gift';

    /**
     * 获取 咨询礼包 类型配置
     * @return array[]
     */
    public function getGiftTypeConfig()
    {
        return [
            [   //  福利专区
                'type' => 1,
                'title_img' => '/test/consult_chat/consult_gift_type1_name.png',
                'icon' => '',
                'title' => '',
            ],
            [   //  专属服务
                'type' => 2,
                'title_img' => '',
                'icon' => '/test/consult_chat/consult_gift_icon.png',
                'title' => '专属服务',
            ],
        ];
    }

    /**
     * 开启了缓存
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $this->whereIn('id', $ids);
            } else
            {
                $this->where('status', 1);
            }

            $questionResult = $this->order('sort ' . $sortType)
                ->column('name,status,minute,type,limit_type,limit_min,exclude_astrs,coin,or_coin,purchase_num,expiration_time,img,notice,sort,num,aid,create_time,update_time', 'id');
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return [];
        }

        return $questionResult;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        $s = ["礼包时长可多次使用，连线过程中礼包时长用尽将自动使用余额继续扣费，扣费标准按咨询师正常单价计算。 ", "礼包不支持和优惠券叠加使用。 ", "礼包使用需要连线前手动选择礼包。", "该礼包仅限和部分咨询师连线使用"];
        $ds = json_encode($s, JSON_UNESCAPED_UNICODE);
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'status', 'minute', 'type', 'limit_type', 'limit_min', 'coin', 'or_coin', 'purchase_num', 'expiration_time', 'sort', 'num', 'aid', 'create_time', 'update_time']);

            if (isset($itemData['exclude_astrs']))
            {
                $excludeAstrs = $itemData['exclude_astrs'] ? explode(',', $itemData['exclude_astrs']) : [];
                $data[$index]['exclude_astrs'] = array_map('intval', $excludeAstrs);
            }

            if (isset($itemData['notice']))
            {
                $data[$index]['notice'] = $itemData['notice'] ? json_decode($itemData['notice'], true) : [];
            }
        }

        return $data;
    }

    /**
     * 获取 连线咨询 礼包首页数据
     * @param int $uid
     * @return array
     * @throws \Exception
     */
    public function getConsultGiftIndexData(int $uid = 0)
    {
        // 已连麦时长 分钟
        $consultDurationMin = 0;
        // 礼包已购买次数
        $consultPayData = [];   // [ 礼包ID => 购买次数 ]
        if ($uid)
        {   // 获取用户已连麦时长
            $rtcDurationData = (new ZyhsConsultChatRtcRecord())->getConsultRtcDurationMin(2, $uid);
            $consultDurationMin = $rtcDurationData['duration_min'];
            $consultPayData = (new AppUserConsultGift())->getUserPayGiftNum($uid);
        }
        $pageData = $this->getListPage(0, 'sort');
        $pageData['data'] = $this->dataInit($pageData['data']);
        $dataList = [];
        foreach ($pageData['data'] as $datum)
        {
            $dataList[$datum['type']][] = $datum;
        }
        $resData = [];
        $giftTypeConfig = $this->getGiftTypeConfig();
        foreach ($giftTypeConfig as $configItem)
        {
            if (!isset($dataList[$configItem['type']]))
            {
                continue;
            }
            $listItem = [];
            $maxLimitMin = 0;
            $nextLevelDurationMinute = 0;   // 下一级别礼包 购买需要满足连线时长
            foreach ($dataList[$configItem['type']] as $dataItem)
            {
                $userPayGiftNum = $consultPayData[$dataItem['id']] ?? 0;
                if ($dataItem['purchase_num'] > 0 && $userPayGiftNum >= $dataItem['purchase_num'])
                {   // 礼包购买限制次数 并且 已购买 达到上限
                    continue;
                }
                $desc = '';
                $status = 1;    // 1=>可购买 2=>不可购买【不满足购买条件】
                if ($dataItem['limit_type'] === 3)
                {
                    $desc = sprintf("连线时长满%d分钟可购买", $dataItem['limit_min']);
                    if ($consultDurationMin < $dataItem['limit_min'])
                    {   // 未满足 购买条件
                        $status = 2;
                        if ($nextLevelDurationMinute === 0)
                        {
                            $nextLevelDurationMinute = $dataItem['limit_min'];
                        } else
                        {   // 去最近的
                            $nextLevelDurationMinute = min($nextLevelDurationMinute, $dataItem['limit_min']);
                        }
                    }
                    $maxLimitMin = max($maxLimitMin, $dataItem['limit_min']);
                }
                if (empty($dataItem['exclude_astrs']))
                {
                    $tags = ['不限咨询师'];
                } else
                {
                    $tags = ['限部分咨询师'];
                }
                if ($dataItem['expiration_time'] > 0)
                {
                    $tags[] = sprintf("有效期：%d天", $dataItem['expiration_time']);
                }


                $listItem[] = [
                    'desc' => $desc,
                    'img' => $dataItem['img'],
                    'title' => $dataItem['name'],
                    'duration_desc' => sprintf("时长%d分钟", $dataItem['minute']),
                    'tags' => $tags,
                    'now_price' => $dataItem['coin'],
                    'old_price' => $dataItem['or_coin'],
                    'id' => $dataItem['id'],
                    'intro' => $this->getConsultGiftIntroStr($dataItem['notice']),
                    'status' => $status,
                    'use_range' => empty($dataItem['exclude_astrs']) ? 0 : 1,
                ];
            }
            $userConsultData = null;
            if ($configItem['type'] === 1 && $uid && $consultDurationMin < $maxLimitMin)
            {
                $userConsultData = [
                    'duration_minute' => $consultDurationMin,
                    'next_level_minute' => $nextLevelDurationMinute - $consultDurationMin,  // 下一级别礼包 购买需要满足连线时长 = 满足购买条件时长 - 当前连线时长
                ];
            }
            $resData[] = [
                'title_img' => $configItem['title_img'],
                'icon' => $configItem['icon'],
                'title' => $configItem['title'],
                'user_consult_data' => $userConsultData,
                'list' => $listItem,
            ];
        }

        return $resData;
    }

    /**
     * @param array $introData
     * @param int $type 1=>购买须知 2=>使用须知
     * @return string
     */
    public function getConsultGiftIntroStr(array $introData, int $type = 1)
    {
        $resStr = '';
        $index = 1;
        if ($type === 1)
        {
            $resStr = '1.礼包购买后不支持退款，请谨慎购买。';
            $index = 2;
        }

        foreach ($introData as $introItem)
        {
            if ($resStr)
            {
                $resStr .= "\r\n";
            }
            $resStr .= sprintf("%d.%s", $index, $introItem);
            $index++;
        }

        return $resStr;
    }
}
